package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ：why
 * @description：
 * @version:
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);
        List<Menu> menus = menuDao.selectByCondition(queryString);
        PageInfo pageInfo = new PageInfo(menus);
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }

    @Override
    public List<Menu> findAllParentMenu() {
        return menuDao.findAllParentMenu();
    }

    @Override
    public List<Menu> findAllIcons() {
        return menuDao.findAllIcons();
    }

    @Override
    public boolean edit(Menu menu) {
        return menuDao.updateMenu(menu);
    }

    @Override
    public boolean add(Menu menu) {
        return menuDao.add(menu);
    }

    @Override
    public Result delete(Integer id) {
        List<Role> menuByRoleMenu = menuDao.findMenuByRoleMenu(id);
        if (menuByRoleMenu != null && menuByRoleMenu.size() > 0) {
            // 查询到了role的列表  说明菜单与角色有关联关系,不能删除
            return new Result(false, MessageConstant.DELETE_MENU_FAIL_ERROR);
        } else {
            boolean result = menuDao.deleteMenuById(id);
            if (result) {
                return new Result(result, MessageConstant.DELETE_MENU_SUCCESS);
            } else {
                return new Result(result, MessageConstant.DELETE_MENU_FAIL);
            }
        }
    }

    @Override
    public List<Menu> findUserMenuByUerName(String username) {
        return menuDao.findMenusByUserName(username);
    }
}
